package com.apps.ubc.cc.ajax;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.apps.datastore.AccountInformationDatastore;
import com.apps.datastore.UBCCourseSpiderDatastore;
import com.apps.datastore.dao.SectionInformationObject;
import com.apps.datastore.dao.WorklistItemObject;

public class WorklistController extends HttpServlet {

	AccountInformationDatastore d = new AccountInformationDatastore();
	UBCCourseSpiderDatastore spiderDatastore = new UBCCourseSpiderDatastore();

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String action = req.getParameter("action");
		Cookie[] cookies = req.getCookies();
		String user = null;
		for (int i = 0; i < cookies.length; i++) {
			if (cookies[i].getName().equals("user"))
				user = cookies[i].getValue();
		}

		String xmlout = "<response>\n";
		if (user != null) {
			if (action.equals("add")) {
				String dept = req.getParameter("dept");
				String course = req.getParameter("course");
				String section = req.getParameter("section");
				WorklistItemObject wio = new WorklistItemObject(dept, course,
						section);
				SectionInformationObject sio = spiderDatastore
						.querySectionFromId(dept, course, section);
				List<SectionInformationObject> siol = d.getWorklistAsSIO(user);
				boolean conflict = isInConflict(siol, sio);
				boolean success = false;
				if (!conflict)
					success = d.addWorklistItem(user, wio);
				if (success)
					xmlout += "\t<message>Item was successfully added to worklist</message>\n";
				else if (conflict)
					xmlout += "\t<message>Unable to add to worklist, due to schedule conflict</message>\n";
				else
					xmlout += "\t<message>Item already exists in worklist</message>\n";
			} else if (action.equals("remove")) {
				String dept = req.getParameter("dept");
				String course = req.getParameter("course");
				String section = req.getParameter("section");
				String start = req.getParameter("start");
				// String end = req.getParameter("end");
				WorklistItemObject wio = new WorklistItemObject(dept, course,
						section);
				boolean success = d.deleteWorklistItem(user, wio);
				if (success) {
					xmlout += "\t<message>Item was successfully removed from worklist</message>\n";
				} else
					xmlout += "\t<message>Item failed to remove from worklist</message>\n";
			} else if (action.equals("get")) {
				List<SectionInformationObject> siol = d.getWorklistAsSIO(user);
				for (Iterator<SectionInformationObject> i = siol.iterator(); i
						.hasNext();) {
					SectionInformationObject sio = i.next();
					xmlout += "\t<item>\n";
					xmlout += "\t\t<dept>" + sio.getDepartmentId()
							+ "</dept>\n";
					xmlout += "\t\t<course>" + sio.getCourseId()
							+ "</course>\n";
					xmlout += "\t\t<section>" + sio.getSectionId()
							+ "</section>\n";
					xmlout += "\t\t<start>" + sio.getStart() + "</start>\n";
					xmlout += "\t\t<end>" + sio.getEnd() + "</end>\n";
					xmlout += "\t\t<day>" + sio.getDay() + "</day>\n";
					xmlout += "\t\t<term>" + sio.getTerm() + "</term>\n";
					xmlout += "\t\t<building>" + sio.getBuilding()
							+ "</building>\n";
					xmlout += "\t\t<room>" + sio.getRoom() + "</room>\n";
					xmlout += "\t</item>\n";
				}
			} else if (action.equals("view")) {
				String email = req.getParameter("email");
				if (d.checkSubscriptionExists(email, user)) {
					List<SectionInformationObject> siol = d
							.getWorklistAsSIO(email);
					for (Iterator<SectionInformationObject> i = siol.iterator(); i
							.hasNext();) {
						SectionInformationObject sio = i.next();
						xmlout += "\t<item>\n";
						xmlout += "\t\t<dept>" + sio.getDepartmentId()
								+ "</dept>\n";
						xmlout += "\t\t<course>" + sio.getCourseId()
								+ "</course>\n";
						xmlout += "\t\t<section>" + sio.getSectionId()
								+ "</section>\n";
						xmlout += "\t\t<start>" + sio.getStart() + "</start>\n";
						xmlout += "\t\t<end>" + sio.getEnd() + "</end>\n";
						xmlout += "\t\t<day>" + sio.getDay() + "</day>\n";
						xmlout += "\t\t<term>" + sio.getTerm() + "</term>\n";
						xmlout += "\t\t<building>" + sio.getBuilding()
								+ "</building>\n";
						xmlout += "\t\t<room>" + sio.getRoom() + "</room>\n";
						xmlout += "\t</item>\n";
					}
				}
			} else if (action.equals("check")) {
				String dept = req.getParameter("dept");
				String course = req.getParameter("course");
				String section = req.getParameter("section");
				WorklistItemObject wio = new WorklistItemObject(dept, course,
						section);
				boolean success = d.checkWorklistItemExists(user, wio);
				if (success)
					xmlout += "\t<exist>true</exist>\n";
				else
					xmlout += "\t<exist>false</exist>\n";
			}
			xmlout += "</response>";

			try {
				resp.setContentType("text/xml; charset=UTF-8");
				resp.getWriter().write(xmlout);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public boolean isInConflict(List<SectionInformationObject> courses,
			SectionInformationObject to_check) {

		if (courses == null || to_check == null) {
			return false;
		}

		String[] i_start = to_check.getStart().split(":");
		String[] i_end = to_check.getEnd().split(":");

		int i_start_hour = Integer.parseInt(i_start[0]);
		int i_start_min = Integer.parseInt(i_start[1]);
		i_start_hour *= 100;
		i_start_hour += i_start_min;

		int i_end_hour = Integer.parseInt(i_end[0]);
		int i_end_min = Integer.parseInt(i_end[1]);
		i_end_hour *= 100;
		i_end_hour += i_end_min;

		for (int i = 0; i < courses.size(); i++) {

			String[] t_start = courses.get(i).getStart().split(":");
			String[] t_end = courses.get(i).getEnd().split(":");

			int t_start_hour = Integer.parseInt(t_start[0]);
			int t_start_min = Integer.parseInt(t_start[1]);
			t_start_hour *= 100;
			t_start_hour += t_start_min;

			int t_end_hour = Integer.parseInt(t_end[0]);
			int t_end_min = Integer.parseInt(t_end[1]);
			t_end_hour *= 100;
			t_end_hour += t_end_min;
			if (isSameTerm(to_check, courses.get(i))) {
				boolean result = inBtwnTime(t_start_hour, t_end_hour,
						i_start_hour)
						&& inBtwnTime(t_start_hour, t_end_hour, i_end_hour);
				System.out.println(result);
				if (result) {
					return true;
				}
			}

		}

		return false;
	}

	private boolean isSameTerm(SectionInformationObject check,
			SectionInformationObject to_check) {

		String check_terms = check.getTerm();
		String to_check_terms = to_check.getTerm();

		String[] c_t_s = check_terms.split("-");
		String[] t_c_t_s = to_check_terms.split("-");

		for (int i = 0; i < c_t_s.length; i++) {
			for (int j = 0; j < t_c_t_s.length; j++) {
				if (c_t_s[i].equals(t_c_t_s[j])) {
					return true;
				}
			}
		}
		return false;

	}

	private boolean inBtwnTime(int start_time, int end_time, int time) {

		if (start_time <= time && time < end_time)
			return true;
		else
			return false;
	}
	
}
